/**
 * @copyright 2018 sinping.com 北京芯平科技股份有限公司. All rights reserved.
 * 本内容仅限于北京芯平科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的.
 */
package com.sinping.qh.service.common.impl;

import com.sinping.qh.service.common.ICacheService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * @类名称: CacheServiceImpl
 * @类描述: cache
 * @作者:杨云博
 * @创建时间:2018/1/8 11:22
 */
@Service
public class CacheServiceImpl implements ICacheService {
    private final static Logger log = LoggerFactory.getLogger(CacheServiceImpl.class);
    @Value("${fx.session.ttl}")
    private int ttlDefault;

    @Autowired
    private JedisPool jedisPool;

    @Override
    public int save(String key, String value, int ttl) {
        Jedis resource = jedisPool.getResource();
        try{
            String setex = resource.setex(key, ttl, value);
            if("OK".equals(setex)){
                return 1;
            }else{
                return 0;
            }
        }catch (Exception e){
           log.error(e.getMessage(), e);
            return 0;
       }finally {
            resource.close();
        }
    }

    @Override
    public int savebyDefaultTtl(String key, String value) {
       return   this.save(key,value,ttlDefault);
    }
    @Override
    public String getValueByKey(String key) {
        Jedis resource = jedisPool.getResource();
        try {
            String fromRedis = resource.get(key);
            if(StringUtils.isNotBlank(fromRedis)){
                return fromRedis;
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            resource.close();
        }
    }
}
